﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain;
using System.Web.Mvc;

namespace WebNext.UI.Utils.Validators
{
	public class CaptchaValidator : IValidator
	{
		private string captchaKey;
		private string captchaValue;

		public CaptchaValidator(string captchaKey, string captchaValue)
		{
			this.captchaKey = captchaKey;
			this.captchaValue = captchaValue;
		}

		public virtual ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();
			if (string.IsNullOrWhiteSpace(this.captchaValue))
			{
				result.AddError(Properties.Resources.CaptchaResultCannotBeEmpty);
			}
			else if (HttpContext.Current.Session[this.captchaKey] == null)
			{
				result.AddError(Properties.Resources.CaptchaResultExpired);
			}
			else
			{
				try
				{
					int storedCaptchaValue = Convert.ToInt32(HttpContext.Current.Session[this.captchaKey]);
					int captchaValue = Convert.ToInt32(this.captchaValue);
					if (storedCaptchaValue != captchaValue)
					{
						result.AddError(Properties.Resources.CaptchaResultInvalid);
					}
				}
				catch
				{
					result.AddError(Properties.Resources.CaptchaResultInvalid);
				}
			}
			HttpContext.Current.Session.Remove(this.captchaKey);
			return result;
		}
	}
}